<template>
  <div class="exchange-connections">
    <div class="page-header">
      <h1>交易所连接配置</h1>
      <p>配置和管理OKX、币安等交易所的连接信息</p>
    </div>

    <!-- 配置卡片列表 -->
    <el-row :gutter="20">
      <el-col
        :xs="24"
        :sm="12"
        :md="8"
        :lg="8"
        :xl="6"
        v-for="exchange in exchanges"
        :key="exchange.id"
      >
        <el-card
          class="exchange-card"
          :class="{ connected: exchange.connected }"
        >
          <!-- 卡片头部 -->
          <template #header>
            <div class="card-header">
              <div class="exchange-info">
                <img
                  :src="exchange.logo"
                  :alt="exchange.name"
                  class="exchange-logo"
                />
                <div>
                  <h3>{{ exchange.name }}</h3>
                  <p class="exchange-type">{{ exchange.type }}</p>
                </div>
              </div>
              <el-tag
                :type="exchange.connected ? 'success' : 'danger'"
                :icon="exchange.connected ? 'SuccessFilled' : 'WarningFilled'"
              >
                {{ exchange.connected ? "已连接" : "未连接" }}
              </el-tag>
            </div>
          </template>

          <!-- 连接状态信息 -->
          <div class="connection-info">
            <div class="info-item">
              <span class="label">连接状态:</span>
              <span
                :class="['status', exchange.connected ? 'success' : 'error']"
              >
                {{ exchange.status }}
              </span>
            </div>
            <div class="info-item" v-if="exchange.connected">
              <span class="label">最后连接:</span>
              <span>{{ exchange.lastConnected }}</span>
            </div>
            <div class="info-item">
              <span class="label">API权限:</span>
              <span>{{ exchange.permissions.join(", ") }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="card-actions">
            <el-button
              type="primary"
              size="small"
              @click="configureExchange(exchange)"
              :icon="Setting"
            >
              配置
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="testConnection(exchange)"
              :loading="exchange.testing"
              :icon="Connection"
            >
              测试连接
            </el-button>
            <el-button
              v-if="exchange.connected"
              type="warning"
              size="small"
              @click="disconnectExchange(exchange)"
              :icon="Remove"
            >
              断开
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加新交易所 -->
    <el-card class="add-exchange-card">
      <el-button
        type="primary"
        size="large"
        @click="addNewExchange"
        :icon="Plus"
        dashed
      >
        添加新的交易所连接
      </el-button>
    </el-card>

    <!-- 配置对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      :title="`配置 ${currentExchange?.name}`"
      width="600px"
      destroy-on-close
    >
      <ExchangeConfigForm
        v-if="currentExchange"
        :exchange="currentExchange"
        @submit="handleConfigSubmit"
        @cancel="configDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ExchangeConfigForm from "./components/ExchangeConfigForm.vue";

// 交易所列表数据
const exchanges = reactive([
  {
    id: "okx",
    name: "OKX",
    type: "中心化交易所",
    logo: "/logos/okx.png",
    connected: true,
    status: "连接正常",
    lastConnected: "2024-01-15 10:30:25",
    permissions: ["读取", "交易"],
    testing: false,
    config: {
      apiKey: "****abc123",
      secretKey: "***",
      passphrase: "***",
      sandbox: false,
      endpoint: "https://www.okx.com",
    },
  },
  {
    id: "binance",
    name: "币安 (Binance)",
    type: "中心化交易所",
    logo: "/logos/binance.png",
    connected: true,
    status: "连接正常",
    lastConnected: "2024-01-15 10:28:15",
    permissions: ["读取", "交易"],
    testing: false,
    config: {
      apiKey: "****def456",
      secretKey: "***",
      testnet: false,
      endpoint: "https://api.binance.com",
    },
  },
  {
    id: "bybit",
    name: "Bybit",
    type: "中心化交易所",
    logo: "/logos/bybit.png",
    connected: false,
    status: "未配置",
    lastConnected: "",
    permissions: [],
    testing: false,
    config: null,
  },
]);

// 对话框状态
const configDialogVisible = ref(false);
const currentExchange = ref(null);

// 配置交易所
const configureExchange = (exchange) => {
  currentExchange.value = exchange;
  configDialogVisible.value = true;
};

// 测试连接
const testConnection = async (exchange) => {
  exchange.testing = true;
  try {
    // 模拟API请求
    await new Promise((resolve) => setTimeout(resolve, 2000));

    // 随机成功/失败
    const success = Math.random() > 0.3;

    if (success) {
      exchange.connected = true;
      exchange.status = "连接正常";
      exchange.lastConnected = new Date().toLocaleString("zh-CN");
      ElMessage.success(`${exchange.name} 连接测试成功`);
    } else {
      exchange.connected = false;
      exchange.status = "连接失败";
      ElMessage.error(`${exchange.name} 连接测试失败，请检查配置`);
    }
  } catch (error) {
    exchange.connected = false;
    exchange.status = "连接异常";
    ElMessage.error(`${exchange.name} 连接测试异常`);
  } finally {
    exchange.testing = false;
  }
};

// 断开连接
const disconnectExchange = async (exchange) => {
  try {
    await ElMessageBox.confirm(
      `确定要断开与 ${exchange.name} 的连接吗？`,
      "确认断开",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    exchange.connected = false;
    exchange.status = "已断开";
    ElMessage.success(`已断开与 ${exchange.name} 的连接`);
  } catch {
    // 用户取消
  }
};

// 添加新交易所
const addNewExchange = () => {
  ElMessage.info("添加新交易所功能开发中...");
};

// 处理配置提交
const handleConfigSubmit = (config) => {
  // 保存配置逻辑
  ElMessage.success("配置保存成功");
  configDialogVisible.value = false;

  // 自动测试连接
  testConnection(currentExchange.value);
};
</script>

<style lang="scss" scoped>
.exchange-connections {
  .page-header {
    margin-bottom: 24px;

    h1 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: var(--el-text-color-primary);
    }

    p {
      margin: 0;
      color: var(--el-text-color-regular);
    }
  }

  .exchange-card {
    margin-bottom: 20px;
    transition: all 0.3s ease;
    border: 2px solid transparent;

    &.connected {
      border-color: var(--el-color-success-light-7);
      background: linear-gradient(
        145deg,
        var(--el-color-success-light-9) 0%,
        var(--el-bg-color) 100%
      );
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .exchange-info {
        display: flex;
        align-items: center;
        gap: 12px;

        .exchange-logo {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          background: var(--el-bg-color-page);
          padding: 4px;
        }

        h3 {
          margin: 0 0 4px 0;
          font-size: 16px;
          font-weight: 600;
        }

        .exchange-type {
          margin: 0;
          font-size: 12px;
          color: var(--el-text-color-regular);
        }
      }
    }

    .connection-info {
      margin: 16px 0;

      .info-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 14px;

        .label {
          color: var(--el-text-color-regular);
        }

        .status {
          &.success {
            color: var(--el-color-success);
          }

          &.error {
            color: var(--el-color-danger);
          }
        }
      }
    }

    .card-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }
  }

  .add-exchange-card {
    text-align: center;
    padding: 40px 20px;
    border: 2px dashed var(--el-border-color);
    background: var(--el-bg-color-page);

    &:hover {
      border-color: var(--el-color-primary);
      background: var(--el-color-primary-light-9);
    }
  }
}

// 响应式
@media (max-width: 768px) {
  .exchange-connections {
    .card-actions {
      .el-button {
        flex: 1;
        min-width: 80px;
      }
    }
  }
}
</style>
